--mqtt
module("mymqtt", package.seeall);
 

function mqttInit(IO, mqttIP)
	--led 
	local gpio_led = IO
	gpio.mode(gpio_led, gpio.OUTPUT) 
	gpio.write(gpio_led, gpio.HIGH)  
	------
	--mqtt
	------
	m = mqtt.Client("Node_MM", 30)
	m:lwt("node", "lwt", 0, 0)
	
	m:on("connect", function(client) 
		m:publish("node", "online", 0, 0)
		m:subscribe("esp8266", 0, function(client) 
			print("subscribe success")
			
		end)
	end)
	
	m:on("offline", function(client)
		print("offline")
		node.restart()
	end)

	m:on("message", function(client, topic, data)
		print(topic .. ": ")
		if data ~= nil then
			print(data)
			if (string.find(data,"OPEN") ~= nil) then
				gpio.write(gpio_led, gpio.LOW)       
			elseif (string.find(data,"CLOSE") ~= nil) then
				gpio.write(gpio_led, gpio.HIGH)            
			elseif (string.find(data,"restart") ~= nil) then
				node.restart()
			end
		end
	end)
	
	m:connect(mqttIP)
end

--m:connect("iot.eclipse.org")

--m:connect("127.0.0.1")

